<!DOCTYPE html><html lang="[&quot;zh-Hans&quot;,&quot;zh-CN&quot;,&quot;default&quot;]"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="reactjs中事件传参"><meta name="keywords" content="react"><meta name="author" content="wenmu"><meta name="copyright" content="wenmu"><title>reactjs中事件传参 | 温木的博客</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.6.1"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.6.1"><link rel="dns-prefetch" href="https://cdn.staticfile.org"><link rel="dns-prefetch" href="https://cdn.bootcss.com"><link rel="dns-prefetch" href="https://creativecommons.org"><link rel="dns-prefetch" href="http://ta.qq.com"><script>(function() {
   var hm = document.createElement("script");
   hm.src = "https://tajs.qq.com/stats?sId=&lt;script type=&quot;text/javascript&quot; src=&quot;http://tajs.qq.com/stats?sId=66523541&quot; charset=&quot;UTF-8&quot;&gt;&lt;/script&gt;";
   var s = document.getElementsByTagName("script")[0];
   s.parentNode.insertBefore(hm, s);
 })();</script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  }
} </script><meta name="generator" content="Hexo 4.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-事件传参技巧"><span class="toc-number">1.</span> <span class="toc-text">1.事件传参技巧</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-扩展阅读"><span class="toc-number">2.</span> <span class="toc-text">2.扩展阅读</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://i.loli.net/2020/02/27/xwaBoOj158MfNyq.jpg"></div><div class="author-info__name text-center">wenmu</div><div class="author-info__description text-center">记录一些在工作中或学习新知识时学到的一些知识点；正所谓好记性不如一个烂笔头，温故而知新！</div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">115</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">52</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">30</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">温木的博客</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus"><a class="site-page" href="/">首页</a><a class="site-page" href="/archives">文章</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a></span></div><div id="post-info"><div id="post-title">reactjs中事件传参</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-01-09</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/react/">react</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>最近公司用 reactjs 做开发，虽然网上很多教程，但实际开发中许多细小的技术点还是需要自己去偶遇</p>
<a id="more"></a>

<h3 id="1-事件传参技巧"><a href="#1-事件传参技巧" class="headerlink" title="1.事件传参技巧"></a>1.事件传参技巧</h3><ul>
<li><strong>问题描述</strong><br>我们在事件中通常需要获取控件的值，通常通过<code>event.target.value</code>的方式来取值，在绑定事件时，event 参数也不需要传递，在方法中直接使用即可。<br>但是，有些时候需要传入一些其他的参数，比如需要循环绑定一些输入框，在绑定 onChange 事件时，需要传入索引<code>index</code>和数据源的索引进行对应</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">onHandleChange(index,event)&#123;</span><br><span class="line">    <span class="keyword">let</span> val=event.target.value</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//关键代码</span></span><br><span class="line">source.map(<span class="function">(<span class="params">item,index</span>)=&gt;</span>&#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">value</span>=<span class="string">&#123;item.name&#125;</span> <span class="attr">onChange</span>=<span class="string">&#123;this.onHandleChange.bind(this,index)&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="xml">&#125;);</span></span><br></pre></td></tr></table></figure>

<ul>
<li><strong>代码解释</strong><br>有的同学应该已经看出区别了，<code>onHandleChange</code>在声明时有两个参数，但在调用时却只传递了一个参数，这就是今天要讲的:<blockquote>
<p><strong>在给方法传递新参数时，方法原有的参数会排在新参数之后</strong></p>
</blockquote>
</li>
</ul>
<p>做过 reactjs 的同学都知道，event 这个参数是不需要手动传递的，直接在方法中声明就可以使用，如下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">onChangeHandle(event)&#123;</span><br><span class="line">      <span class="keyword">let</span> val=event.target.value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">render()&#123;</span><br><span class="line">  <span class="keyword">return</span> (<span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line">    &lt;input type="text" onChange=&#123;this.onChangeHandle.bind(this)&#125; /&gt;</span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">div</span>&gt;</span>)</span></span><br><span class="line"><span class="xml">&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="2-扩展阅读"><a href="#2-扩展阅读" class="headerlink" title="2.扩展阅读"></a>2.扩展阅读</h3><ul>
<li>描述<br>在自定义组件时，组件的事件由父组件传入，但为了方便，我们可能在自定义组件中把需要的数据回传给富组件传递过来的方法，如下 dropdwon 控件</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">"react"</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">WDropdownlist</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">  <span class="keyword">constructor</span>(props) &#123;</span><br><span class="line">    <span class="keyword">super</span>(props);</span><br><span class="line">    <span class="keyword">this</span>.state = &#123;</span><br><span class="line">      value: <span class="string">"-1"</span>,</span><br><span class="line">      text: <span class="string">"全部"</span>,</span><br><span class="line">      selectedValue: <span class="number">0</span>,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  componentWillReceiveProps(nextProps) &#123;</span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;</span><br><span class="line">      selectedValue: nextProps.selectedValue,</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">  componentWillMount() &#123;</span><br><span class="line">    <span class="keyword">this</span>.setState(&#123;</span><br><span class="line">      selectedValue: <span class="keyword">this</span>.props.selectedValue,</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">  handleChange(event) &#123;</span><br><span class="line">    <span class="keyword">let</span> _self = <span class="keyword">this</span>;</span><br><span class="line">    <span class="keyword">let</span> _props = _self.props;</span><br><span class="line">    <span class="keyword">this</span>.setState(&#123; <span class="attr">selectedValue</span>: event.target.value &#125;);</span><br><span class="line">    <span class="keyword">const</span> currentIndex = event.target.selectedIndex;</span><br><span class="line">    <span class="keyword">const</span> targetItems = <span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(_props.dataSource));</span><br><span class="line">    _props.onChange &amp;&amp;</span><br><span class="line">      _props.onChange.call(_self, &#123;</span><br><span class="line">        currentIndex: currentIndex,</span><br><span class="line">        currentItem: targetItems[currentIndex],</span><br><span class="line">      &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">  render() &#123;</span><br><span class="line">    <span class="keyword">const</span> self = <span class="keyword">this</span>;</span><br><span class="line">    <span class="keyword">const</span> props = self.props;</span><br><span class="line">    <span class="keyword">var</span> state = self.state;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      &lt;select</span><br><span class="line">        className=&#123;props.className&#125;</span><br><span class="line">        style=&#123;props.style&#125;</span><br><span class="line">        disabled=&#123;props.disabled&#125;</span><br><span class="line">        onChange=&#123;self.handleChange.bind(self)&#125;</span><br><span class="line">        name=&#123;props.name&#125;</span><br><span class="line">        value=&#123;state.selectedValue&#125;</span><br><span class="line">      &gt;</span><br><span class="line">        &#123;!props.dataSource || props.dataSource.length == <span class="number">0</span> ? (</span><br><span class="line">          &lt;option value=&#123;<span class="keyword">this</span>.state.value&#125;&gt;&#123;<span class="keyword">this</span>.state.text&#125;&lt;<span class="regexp">/option&gt;</span></span><br><span class="line"><span class="regexp">        ) : (</span></span><br><span class="line"><span class="regexp">          props.dataSource.map((item, index) =&gt; (</span></span><br><span class="line"><span class="regexp">            &lt;option key=&#123;index&#125; value=&#123;item[props.valueField]&#125;&gt;</span></span><br><span class="line"><span class="regexp">              &#123;item[props.textField]&#125;</span></span><br><span class="line"><span class="regexp">            &lt;/</span>option&gt;</span><br><span class="line">          ))</span><br><span class="line">        )&#125;</span><br><span class="line">      &lt;<span class="regexp">/select&gt;</span></span><br><span class="line"><span class="regexp">    );</span></span><br><span class="line"><span class="regexp">  &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br><span class="line"><span class="regexp">WDropdownlist.defaultProps = &#123;</span></span><br><span class="line"><span class="regexp">  style: &#123;&#125;,</span></span><br><span class="line"><span class="regexp">  valueField: "value",</span></span><br><span class="line"><span class="regexp">  textField: "text",</span></span><br><span class="line"><span class="regexp">  selectedValue: 0,</span></span><br><span class="line"><span class="regexp">  disabled: false,</span></span><br><span class="line"><span class="regexp">&#125;;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>组件调用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> WDropdwonList <span class="keyword">from</span> <span class="string">'../wigets/w-dropdwon-list.js'</span>;</span><br><span class="line"><span class="comment">//第一个参数就是下面调用控件时传递的参数，item是定义组件时传递的当前选中项对象</span></span><br><span class="line">onChangeHandle(currentMan,item)&#123;</span><br><span class="line">&#125;</span><br><span class="line">render()&#123;</span><br><span class="line">    <span class="keyword">return</span> (<span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml">       otherSource.map((currentMan,index)=&gt;&#123;</span></span><br><span class="line">        &lt;WDropdwonList onChange=&#123;this.onChangeHandle.bind(this,currentMan)&#125;</span><br><span class="line">                dataSource=&#123;this.state.source&#125;</span><br><span class="line">                textField='Display'</span><br><span class="line">                valueField='Value'</span><br><span class="line">                selectedValue=&#123;currentSubsystem['PointRoles'][key]||'-1'&#125;  &gt;</span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">WDropdwonList</span>&gt;</span></span></span><br><span class="line"><span class="xml">&#125;)</span></span><br><span class="line">&lt;div&gt;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>讲解：<br>下拉框事件中 ，当前选中项经常使用，因此封装到了自定义组件中，但是在使用自定义组件时，会需要传递进去数据源的一些其他参数，比如上面的<code>currentMan</code>,该参数在调用事件方法时，像正常一样传递，没区别，只是在声明事件方法时，事件方法“隐含”的参数放在新传递的参数之后就行，如上面事件方法的定义，item 就是组件内部传递出来的参数,在调用时，是不需要在外面显示传递的</li>
</ul>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">wenmu</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://blog.wangpengpeng.site/2020/01/09/reactjs%E4%B8%AD%E4%BA%8B%E4%BB%B6%E4%BC%A0%E5%8F%82/">http://blog.wangpengpeng.site/2020/01/09/reactjs%E4%B8%AD%E4%BA%8B%E4%BB%B6%E4%BC%A0%E5%8F%82/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://blog.wangpengpeng.site">温木的博客</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/react/">react</a></div><div class="post-qr-code"><div class="post-qr-code-item"><img class="post-qr-code__img" src="https://i.loli.net/2020/02/27/hOBzIxFDJMCrmtN.jpg"><div class="post-qr-code__desc">微信打赏</div></div></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/01/09/Swagger-UI%E5%85%A5%E9%97%A8%E9%83%A8%E7%BD%B2/"><i class="fa fa-chevron-left">  </i><span>Swagger UI入门部署</span></a></div><div class="next-post pull-right"><a href="/2020/01/09/create-react-app%E9%A1%B9%E7%9B%AE%E9%83%A8%E7%BD%B2%E5%88%B0Github-Pages/"><span>create-react-app项目部署到Github Pages</span><i class="fa fa-chevron-right"></i></a></div></nav><div id="vcomment"></div><script src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script><script src="https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js"></script><script>var notify = 'false' == true ? true : false;
var verify = 'false' == true ? true : false;
var GUEST_INFO = ['nick','mail','link'];
var guest_info = 'nick,mail,link'.split(',').filter(function(item){
  return GUEST_INFO.indexOf(item) > -1
});
guest_info = guest_info.length == 0 ? GUEST_INFO :guest_info;
window.valine = new Valine({
  el:'#vcomment',
  notify:notify,
  verify:verify,
  appId:'U1QqpeQNuBnRsfygHk1GQ30q-gzGzoHsz',
  appKey:'dunDQzEseDzgsKgw4qLQcog1',
  placeholder:'支持markdown！',
  avatar:'wavatar',
  guest_info:guest_info,
  pageSize:'20',
  lang: 'zh-cn'
})</script></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2019 - 2020 By wenmu</div><div class="framework-info"><span>驱动 - </span><a href="http://hexo.io" target="_blank" rel="noopener"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a href="https://github.com/Molunerfinn/hexo-theme-melody" target="_blank" rel="noopener"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv">该文访问量<span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.6.1"></script><script src="/js/fancybox.js?version=1.6.1"></script><script src="/js/sidebar.js?version=1.6.1"></script><script src="/js/copy.js?version=1.6.1"></script><script src="/js/fireworks.js?version=1.6.1"></script><script src="/js/transition.js?version=1.6.1"></script><script src="/js/scroll.js?version=1.6.1"></script><script src="/js/head.js?version=1.6.1"></script><script>if(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
}</script></body></html>